import React, { useState, useEffect } from "react";
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { Upload } from 'antd'
import { func, string } from "prop-types";
import { beforeUploadImage, uploadUrl } from './upload.util'
import './index.less';


const UploadComp = props => {
  const [loading, setLoading] = useState(false)
  const [avatar, setAvatar] = useState('')

  useEffect(() => {
    setAvatar(props.avatar)
  }, [props.avatar])


  const handleChange = info => {
    // 状态有：uploading done error removed，被 beforeUpload 拦截的文件没有 status 属性
    if (info.file.status === 'uploading') {
      return setLoading(true);
    }
    if (info.file.status === 'done') {
      const res = info.file.response;
      let imageUrl = "";
      if (res.data) {
        imageUrl = res.data[0];
        props.onUploadOk && props.onUploadOk(imageUrl)
        setAvatar(imageUrl)
        setLoading(false)
      }
    }
  };
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );
  return (
    <Upload
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      action={uploadUrl}
      accept="image/*"
      beforeUpload={beforeUploadImage}
      onChange={handleChange}
    >
      {avatar ? <img src={avatar} alt="avatar" style={{ width: '100%', maxHeight: '100%' }} /> : uploadButton}
    </Upload>
  );
};

UploadComp.propTypes = {
  avatar: string,
  onUploadOk: func,
};

export default UploadComp;
